package com.iot.geteway.filters;

import com.iot.geteway.cache.ApiControlCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Author 咕唧
 * @Date 2022/7/22 9:55
 * @Version 1.0
 */
@Component
public class ApiControlFilter implements GlobalFilter, Ordered {

    private ApiControlCache apiControlCache;

    @Autowired
    public void setApiControlCache(ApiControlCache apiControlCache) {
        this.apiControlCache = apiControlCache;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求的路径
        String path = exchange.getRequest().getURI().getPath();
        //不包含过滤条件放行
        return Mono.just(apiControlCache.getApiSet())
                .filter(collection -> !collection.contains(path))
                .map(r -> chain.filter(exchange))
                .defaultIfEmpty(exchange.getResponse().writeAndFlushWith(
                        Mono.just(Mono.just(
                                DefaultDataBufferFactory
                                        .sharedInstance
                                        .allocateBuffer().write("当前网络质量差，请检查网络".getBytes(StandardCharsets.UTF_8))))))
                .flatMap(r -> r);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
